// TODO 还没有处理加载失败和删除失败的情况

// 加载评论
function renderComments() {
    $.ajax({
        url: '/admin/comments',
        success: (res) => {
            console.log(res);
            let str = '';
            res.data.forEach((element) => {
                str += `
                <tr>
                <td>${element.id}</td>
                <td>${element.uname}</td>
                <td>${element.content}</td>
                <td>${element.cdate.substring(0, 10)}</td>
                <td>
                    <button data-id="${
                        element.id
                    }" type="button" class="delbutton layui-btn layui-btn-xs layui-btn-danger">删除</button>
                </td>
              </tr>
                `;
            });
            $('#comment-tbody').html(str);
        },
    });
}

renderComments();

// 删除操作
$('#comment-tbody').on('click', '.delbutton', function (ev) {
    let delID = $(this).data('id');
    console.log(delID)
    layer.confirm(
        '确定要删除吗？',
        { icon: 2},
        function (index) {
            $.ajax({
                url: '/admin/comments/' + delID,
                type: 'DELETE',
                success: (res) => {
                    console.log(res)
                    if (res.status === 0) {
                        console.log(res);
                        renderComments();
                    }
                },
                // error: function (xhr, status, err) {
                //     console.log(xhr);
                //     console.log(status);
                //     console.log(err);
                // },
                // complete: function (xhr, status) {
                //     console.log(xhr);
                //     console.log(status);
                // },
            });
            layer.close(index);
        }
    );
});
